#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证API控制器
处理用户认证相关的HTTP请求
"""

from flask import Blueprint, request, jsonify
from services.auth_service import AuthService
from database.mysql_manager import mysql_manager
from utils.validators import validate_login_data, validate_register_data
from utils.response_helper import success_response, error_response

# 创建蓝图
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')

# 初始化服务
def get_auth_service():
    """获取认证服务实例"""
    db_session = mysql_manager.get_session()
    return AuthService(db_session)


@auth_bp.route('/login', methods=['POST'])
def login():
    """
    用户登录
    
    POST /api/auth/login
    {
        "username": "string",
        "password": "string"
    }
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        # 验证数据
        validation_result = validate_login_data(data)
        if not validation_result['valid']:
            return error_response(validation_result['message'], 400)
        
        # 认证用户
        auth_service = get_auth_service()
        result = auth_service.authenticate_user(
            data.get('username'),
            data.get('password')
        )
        
        if result['success']:
            return success_response(
                data=result['user'],
                message=result['message']
            )
        else:
            return error_response(result['message'], 401)
            
    except Exception as e:
        return error_response(f'Login error: {str(e)}', 500)


@auth_bp.route('/register', methods=['POST'])
def register():
    """
    用户注册
    
    POST /api/auth/register
    {
        "username": "string",
        "password": "string",
        "email": "string",
        "role": "string"
    }
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        # 验证数据
        validation_result = validate_register_data(data)
        if not validation_result['valid']:
            return error_response(validation_result['message'], 400)
        
        # 注册用户
        auth_service = get_auth_service()
        result = auth_service.register_user(data)
        
        if result['success']:
            return success_response(
                data={'user_id': result['user_id']},
                message=result['message']
            )
        else:
            return error_response(result['message'], 400)
            
    except Exception as e:
        return error_response(f'Registration error: {str(e)}', 500)


@auth_bp.route('/user/<user_id>', methods=['GET'])
def get_user(user_id):
    """
    获取用户信息
    
    GET /api/auth/user/{user_id}
    """
    try:
        auth_service = get_auth_service()
        result = auth_service.get_user_by_id(user_id)
        
        if result['success']:
            return success_response(
                data=result['user'],
                message='User retrieved successfully'
            )
        else:
            return error_response(result['message'], 404)
            
    except Exception as e:
        return error_response(f'Error fetching user: {str(e)}', 500)


@auth_bp.route('/users', methods=['GET'])
def get_users():
    """
    获取所有用户
    
    GET /api/auth/users
    """
    try:
        auth_service = get_auth_service()
        result = auth_service.get_all_users()
        
        if result['success']:
            return success_response(
                data={
                    'users': result['users'],
                    'count': result['count']
                },
                message='Users retrieved successfully'
            )
        else:
            return error_response(result['message'], 500)
            
    except Exception as e:
        return error_response(f'Error fetching users: {str(e)}', 500)


@auth_bp.route('/logout', methods=['POST'])
def logout():
    """
    用户登出
    
    POST /api/auth/logout
    """
    try:
        # 这里可以添加token失效逻辑
        return success_response(
            message='Logout successful'
        )
    except Exception as e:
        return error_response(f'Logout error: {str(e)}', 500)